package com.cedarhd.finance.msg.domain.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cedarhd.finance.msg.common.enums.CacheConstants;
import com.cedarhd.finance.msg.common.utils.HttpUtil;
import com.cedarhd.finance.msg.dto.TemplateMsgDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Evan
 * @date 2018/3/8
 */
@Service
public class SmsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${jpushPlus.apiKey}")
    private String apiKey;

    @Value("${jpushPlus.masterSecret}")
    private String masterSecret;

    @Value("${jpushPlus.codeUrl}")
    private String codeUrl;

    @Value("${jpushPlus.tempMsgUrl}")
    private String msgUrl;

    private Logger logger = LoggerFactory.getLogger(SmsService.class);


    /**
     * 发送验证码
     * @param mobile
     * @param tempId
     * @return
     */
    public Boolean sendVerificationCode(String mobile,String tempId){
        // 发送验证码
        String default_temp_id = "1";

        if(StringUtils.isBlank(tempId)){
            tempId = default_temp_id;
        }

        Map<String, Object> params = new HashMap<>(2);
        params.put("temp_id", tempId);
        params.put("mobile", mobile);

        //调用极光接口
        String response = postToJiguan(codeUrl,params);
        logger.info("sendVerificationCode response = {}",response);

        if(response == null) {
            return false;
        }

        JSONObject jsonObject = JSON.parseObject(response);
        if(jsonObject.containsKey("error")){
            logger.error("发送信息验证码失败! mobile = {}",mobile);
            return false;
        }

        String msgId = jsonObject.getString("msg_id");
        stringRedisTemplate.opsForValue().set(CacheConstants.SEND_MOBILE.getValue() + mobile, msgId, 300, TimeUnit.SECONDS);

        return true;

    }

    /**
     * 验证验证码
     * @param mobile
     * @param code
     * @return
     */
    public Boolean validateCode(String mobile,String code){
        Boolean result = false;
        String msg_Id = stringRedisTemplate.opsForValue().get(CacheConstants.SEND_MOBILE.getValue() + mobile);
        logger.info("validateCode msgId:{}", msg_Id);
        if(StringUtils.isBlank(msg_Id)){
            logger.info("该手机号msgId为空，手机号为：{}", mobile);
            return result;
        }

        Map<String, Object> params = new HashMap<>(1);
        params.put("code",code);
        String validateUrl = codeUrl+"/"+msg_Id+"/valid";
        String response = postToJiguan(validateUrl,params);

        logger.info("validateCode response = {}",response);
        if(response == null){
            logger.error("validateCode error mobile={}",mobile);
            return result;
        }
        JSONObject jsonObject = JSON.parseObject(response);
        result = jsonObject.getBoolean("is_valid");
        stringRedisTemplate.delete(CacheConstants.SEND_MOBILE + mobile);

        return result;
    }

    /**
     * 发送模版短信
     * @param dto
     * @return
     */
    public Boolean sendTemplateMsg(TemplateMsgDTO dto){
        Map<String, Object> params = new HashMap<>(2);
        params.put("temp_id", dto.getTempId());
        params.put("mobile", dto.getMobile());
        params.put("temp_para",dto.getTempPara());

        String response = postToJiguan(msgUrl,params);
        logger.info("sendTemplateMsg response = {}",response);
        if(response == null){
            return false;
        }

        JSONObject jsonObject = JSON.parseObject(response);
        if(jsonObject.containsKey("error")){
            return false;
        }

        return true;
    }

    /**
     * 调用极光接口
     * @param params
     * @return
     */
    private String  postToJiguan(String url,Map<String,Object> params){
        String content = apiKey+":"+masterSecret;
        String base64_auth_string = Base64.getEncoder().encodeToString(content.getBytes());

        Map<String,String> header = new HashMap<>(2);
        header.put("Authorization","Basic " + base64_auth_string);
        String response =  HttpUtil.postHttpBody(url,JSON.toJSONString(params),header);

        return response;
    }




}
